
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include "../iface/debug.h"
#include "../utils/BaseConvert.h"
#include "../utils/StringUtils.h"
#include "ECDSAPublicKey.h"
#include "ECDSAPrivateKey.h"

/** Constructor for a blank ECDSA private key. */
ECDSAPrivateKey::ECDSAPrivateKey()
{
   key = NULL;
   keyname = NULL;
}

/** Constructor for a blank ECDSA private key with a name.
 * 
 * @param name The name to attach to the blank key. */
ECDSAPrivateKey::ECDSAPrivateKey(const char *name)
{
   key = NULL;
   keyname = NULL;
   setKeyName(name);
}

/** Copy constructor for an ECDSA private key.
 * 
 * @param other The ECDSA private key to copy from. */
ECDSAPrivateKey::ECDSAPrivateKey(const ECDSAPrivateKey &other)
{
   key = EC_KEY_new();
   if (key == NULL)
   {
      errprint("ECDSA_new failed");
      return;
   }
   copyECDSASSLPrivateKey(key, other.key);
   keyname = NULL;
   setKeyName(other.keyname);
}

/** Construct the ECDSA private key from a PEM encoded PKCS #8 text
 * format ECDSA private key.
 * 
 * @param pemtext The PEM encoded PKCS #8 text that represents an
 * ECDSA private key, from which this key is to be constructed.
 * 
 * @param name The name to be attached to the key, once
 * constructed. */
ECDSAPrivateKey::ECDSAPrivateKey(const char *pemtext, const char *name)
{
   importKeyFromASCII(pemtext, name);
}

/** Construct the ECDSA private key from an encrypted and passworded
 * PEM encoded PKCS #8 text format ECDSA private key.
 * 
 * @param pemtext The PEM encoded PKCS #8 text that represents an
 * ECDSA public key, from which this key is to be constructed.
 * 
 * @param password The password to decrypt the PEM encoded PKCS #8
 * text that represents the ECDSA public key.
 * 
 * @param name The name to be attached to the key, once
 * constructed. */
ECDSAPrivateKey::ECDSAPrivateKey(const char *pemtext, const char *password, const char *name)
{
   importKeyFromASCIIWithPassword(pemtext, password, name);
}

/** Construct the ECDSA private key from an ECDSA private key in SSL
 * format.
 * 
 * @param prvkey The SSL format ECDSA private key to construct this
 * key from.
 * 
 * @param name The name to be attached to the key, once
 * constructed. */
ECDSAPrivateKey::ECDSAPrivateKey(EC_KEY *prvkey, const char *name)
{
   key = EC_KEY_new();
   if (key == NULL)
   {
      errprint("EC_KEY_new failed");
      return;
   }
   if (copyECDSASSLPrivateKey(key, prvkey))
   {
      errprint("EC_KEY copy failed");
      SSLCheckError(0);
      return;
   }
   keyname = NULL;
   setKeyName(name);
}

/** Copy assignment operator for an ECDSA private key.
 * 
 * @param other The ECDSA private key to copy from. */
ECDSAPrivateKey &ECDSAPrivateKey::operator=(const ECDSAPrivateKey &other)
{
   key = EC_KEY_new();
   if (key == NULL)
   {
      errprint("EC_KEY_new failed");
      return *this;
   }
   if (copyECDSASSLPrivateKey(key, other.key))
   {
      errprint("EC_KEY copy failed");
      SSLCheckError(0);
      return *this;
   }
   keyname = NULL;
   setKeyName(other.keyname);
   return *this;
}

/** Destructor for the ECDSA private key. */
ECDSAPrivateKey::~ECDSAPrivateKey()
{
   if (key) EC_KEY_free(key);
   key = NULL;
   if (keyname) free((void *)keyname);
   keyname = NULL;
}

/** Get a copy of the private key as an SSL format object.
 * 
 * @param[out] prvkey A pointer to a place to put a pointer to the new
 * SSL format ECDSA private key which is a copy of this key. The
 * responsibility for freeing the new ECDSA in SSL format is
 * transferred to the caller.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPrivateKey::getSSLKeyComponents(EC_KEY **prvkey) const
{
   *prvkey = EC_KEY_new();
   if ((*prvkey) == NULL)
   {
      errprint("ECDSA_new failed");
      return -1;
   }
   return copyECDSASSLPrivateKey(*prvkey, key);
}

/** Get a copy of the private key in PEM encoded PKCS #8 text format.
 * 
 * @param[out] pemtext A pointer to a place to put a pointer to the
 * exported key in PEM encoded PKCS #8 text format. The responsibility
 * for freeing the new string is transferred to the caller.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPrivateKey::getPEMKeyData(char **pemtext) const
{
   return getPEMKeyData(pemtext, NULL);
}

/** Get a copy of the public key in PEM encoded and encrypted PKCS #8
 * text format, protected with the given password.
 * 
 * @param[out] pemtext A pointer to a place to put a pointer to the
 * exported key in encrypted PEM encoded PKCS #8 text format. The
 * responsibility for freeing the new string is transferred to the
 * caller.
 * 
 * @param password The password to encrypt and decrypt the key with.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPrivateKey::getPEMKeyData(char **pemtext, const char *password) const
{
   char *data;
   int damt;
   int retval = 0;
   BIO *bo = BIO_new(BIO_s_mem());
   if (!PEM_ASN1_write_bio((i2d_of_void *)i2d_ECPrivateKey, PEM_STRING_ECPRIVATEKEY, bo, (char *)key, (password) ? EVP_des_ede3_cbc() : NULL, NULL, 0, 0, (void *)password))
   {
      retval = 1;
      errprint("could not export private key (password optional)");
      SSLCheckError();
      goto bioshutdown;
   }
   SSLCheckError();
   damt = BIO_get_mem_data(bo, &data);
   (*pemtext) = (char *)malloc(sizeof(char)*(damt+1));
   memcpy((*pemtext), data, sizeof(char)*(damt+1));
   (*pemtext)[damt] = '\0';
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   return retval;
}

/** Compare this PrivateKey to a PublicKey, and see if they are part
 * of the same key pair (one decrypts any content encrypted by the
 * other).
 * 
 * @param pubkey The public key to compare to this private key to see
 * if they make a valid pair.
 * 
 * @return 1 if they make a matching pair of keys, 0 if they do not,
 * and negative values represent errors. */
int ECDSAPrivateKey::compareKeyBelongs(PublicKey *pubkey) const
{
   if (pubkey == NULL)
   {
      errprint("comparing against NULL key");
      return 0;
   }
   switch (pubkey->getKeyType())
   {
      case KEY_TYPE_PUBLIC_ECDSA:
      {
         EC_KEY *ecdsaKeyOther = EC_KEY_new();
         getSSLKeyComponents(&ecdsaKeyOther);
         ((ECDSAPublicKey *)pubkey)->getSSLKeyComponents(&ecdsaKeyOther);
         int retval = EC_KEY_check_key(ecdsaKeyOther);
         EC_KEY_free(ecdsaKeyOther);
         SSLCheckError();
         switch (retval)
         {
            case -2:
               errprint("key compare operation not supported (EVP_PKEY_cmp())");
               break;
            case -1:
               errprint("tried to compare different key types (EVP_PKEY_cmp())");
               return 0;
            case 0:
               return 0;
            case 1:
               return 1;
         }
         return 0;
         break;
      }
      default:
      {
         return 0;
         break;
      }
   }
}

/** Copy an SSL format private key.
 * 
 * @param[out] dst Pointer to an initialised blank SSL format ECDSA
 * key to copy into.
 * 
 * @param src Pointer to an existing SSL format ECDSA private key to
 * copy from.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPrivateKey::copyECDSASSLPrivateKey(EC_KEY *dst, EC_KEY *src)
{
   if (dst == NULL) { errprint("NULL private key destination"); return -1; }
   if (src == NULL) { errprint("NULL private key source"); return 1; }
   if (EC_KEY_set_group(dst, EC_KEY_get0_group(src)) == 0)
   {
      errprint("Failed to copy%s key group", (EC_KEY_get0_group(src)) ? "" : " NULL");
      return -1;
   }
   if (EC_KEY_set_private_key(dst, EC_KEY_get0_private_key(src)) == 0)
   {
      errprint("Failed to copy%s private key", (EC_KEY_get0_private_key(src)) ? "" : " NULL");
      return -1;
   }
   if (EC_KEY_set_public_key(dst, EC_KEY_get0_public_key(src)) == 0)
   {
      errprint("Failed to copy%s public key", (EC_KEY_get0_public_key(src)) ? "" : " NULL");
      return -1;
   }
   return 0;
}

/** Import and name an ECDSA private key from an ECDSA private key in
 * encrypted PEM format PKCS #8.
 * 
 * @param pemtext The PEM encoded PKCS #8 text that represents an
 * ECDSA public key, from which this key is to be constructed.
 * 
 * @param password The password to decrypt the PEM encoded PKCS #8
 * text that represents the ECDSA public key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPrivateKey::importPrivateKeyWithOptionalPassword(const char *pemtext, const char *password)
{
   if (!key) key = EC_KEY_new();
   int retval = 0;
   BIO *bo = BIO_new_mem_buf((void *)pemtext, -1);
   if (!PEM_ASN1_read_bio((d2i_of_void *)d2i_ECPrivateKey, PEM_STRING_ECPRIVATEKEY, bo, (void **)(&key), 0, (void *)password))
   {
      retval = 1;
      errprint("could not import private key (password optional)");
      SSLCheckError();
      goto bioshutdown;
   }
   SSLCheckError();
bioshutdown:
   BIO_set_close(bo, BIO_CLOSE);
   BIO_free(bo);
   return retval;
}

/** Import an ECDSA private key from some PEM format PKCS #8 text.
 * 
 * @param text The PEM encoded PKCS #8 text that represents an ECDSA
 * public key, from which this key is to be constructed.
 * 
 * @param name The name to be attached to the key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPrivateKey::importKeyFromASCII(const char *text, const char *name)
{
   return importKeyFromASCIIWithPassword(text, NULL, name);
}

/** Import and name an ECDSA private key from an ECDSA private key in
 * encrypted PEM format PKCS #8.
 * 
 * @param text The PEM encoded PKCS #8 text that represents an ECDSA
 * public key, from which this key is to be constructed.
 * 
 * @param password The password to decrypt the PEM encoded PKCS #8
 * text that represents the ECDSA public key.
 * 
 * @param name The name to be attached to the key.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPrivateKey::importKeyFromASCIIWithPassword(const char *text, const char *password, const char *name)
{
   setKeyName(name);
   int retval = importPrivateKeyWithOptionalPassword(text, password);
   return retval;
}

/** Export an ECDSA private key to some PEM format PKCS #8 text.
 * 
 * @param[out] text A pointer to a place to put a pointer to the
 * exported key in PEM encoded PKCS #8 text format. The responsibility
 * for freeing the new string is transferred to the caller.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPrivateKey::exportKeyToASCII(char **text) const
{
   return getPEMKeyData(text);
}

/** Export an ECDSA private key to some PEM format PKCS #8 text
 * encrypted with the given password.
 * 
 * @param[out] text A pointer to a place to put a pointer to the
 * exported key in encrypted PEM encoded PKCS #8 text format. The
 * responsibility for freeing the new string is transferred to the
 * caller.
 * 
 * @param password The password to encrypt and decrypt the key with.
 * 
 * @return Returns zero on success, non-zero on failure. */
int ECDSAPrivateKey::exportKeyToASCIIWithPassword(char **text, const char *password) const
{
   return getPEMKeyData(text, password);
}
